<template>
    <LayOut :bread="[{
        title: '文档',
    }]">
        <el-row>
            <el-col :span="12">
                <el-input v-model="input3" style="max-width: 600px" placeholder="请输入书名" size="large"
                    @keyup.enter="searchBook" clearable>
                    <template #append>
                        <el-button type="primary" @click="searchBook"><el-icon>
                                <Search />
                            </el-icon>&nbsp;搜索</el-button>
                    </template>
                </el-input>
            </el-col>
            <el-col :span="12" style="text-align: right;">
                <el-button type="primary" size="large" @click="dialogVisible = true">新增书籍</el-button>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="6" style="margin-bottom: 20px;" v-for="item in booksList" :key="item.id">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>{{ item.name }}</span>
                            <el-popover placement="top-start" :width="200" trigger="hover">
                                <template #reference>
                                    <el-icon class="more">
                                        <MoreFilled />
                                    </el-icon>
                                </template>
                                <ul class="popour-list">
                                    <li class="popour-list-item" @click="() => {
        selectedBookId = item.id;
        reNamingVisile = true;
    }">重命名</li>
                                    <li class="popour-list-item" @click="() => {
        selectedBookId = item.id;
        deleteVisile = true;
    }">删除</li>
                                </ul>
                            </el-popover>
                        </div>
                    </template>
                    <div class="card-content" @click="goToDetail(item)">
                        <p class="intro">{{ item.intro }}</p>
                        <p class="time">作者：{{ item.nickname }}</p>
                        <p class="time">创建时间：{{ dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss') }}</p>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog v-model="dialogVisible" title="新增书籍" width="500">
            <el-form :model="form" label-width="auto" style="max-width: 600px" ref="ruleFormRef">
                <el-form-item label="名称" prop="name" required>
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="简介" prop="intro">
                    <el-input v-model="form.intro" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit(ruleFormRef)">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="reNamingVisile" title="重新命名" width="500">
            <el-form :model="form2">
                <el-form-item label="书名">
                    <el-input v-model="form2.name" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="reNamingVisile = false">取消</el-button>
                    <el-button type="primary" @click="reNameHandle">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="deleteVisile" title="删除" width="500">
            <span>请您确定是否删除?</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="deleteVisile = false">取消</el-button>
                    <el-button type="primary" @click="deleteCBookHandle">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </LayOut>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import LayOut from '../components/LayOut.vue'
import { Search } from '@element-plus/icons-vue'
import { ElLoading, ElMessage } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import service from '../service/index'
import { to } from '../plugin/index'
import type { IBookItemDataModal } from '../type'
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';

const router = useRouter();

const { getBooks, addBooks, updateBook } = service;

const input3 = ref('')
const dialogVisible = ref(false)
const form = reactive({
    name: '',
    intro: '',
})
const form2 = reactive({
    name: '',
})
const ruleFormRef = ref<FormInstance>()
const booksList = ref<IBookItemDataModal[]>([])
const reNamingVisile = ref<boolean>(false);
const deleteVisile = ref<boolean>(false);
// const visible = ref<boolean>(false);
const selectedBookId = ref<string>('');
const selectedBookName = ref<string>('');

// const toogleVisible = (flag: boolean) => {
//     visible.value = flag;
// }

// const moreClick = (item) => {
//     selectedBookId.value = item.id;
//     console.log(selectedBookId.value);

//     visible.value = true;
// }

const getBooksHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(getBooks());
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
        console.log(result);
        booksList.value = result.data;
    } else {
        ElMessage.error('获取数据失败');
        console.error(err);
    }
}

const addBookssHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(addBooks(form));
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
        dialogVisible.value = false;
        ElMessage.success('添加成功');
        getBooksHandle();
    } else {
        ElMessage.error('添加失败');
        console.error(err);
    }
}

const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            addBookssHandle();
        } else {
            console.log('error submit!', fields)
        }
    })
}

const goToDetail = (item: IBookItemDataModal) => {
    router.push({
        path: '/document/detail',
        query: { id: item.id, name: item.name }
    })
}

const searchBook = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(getBooks({ name: input3.value }));
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
        booksList.value = result.data;
    } else {
        ElMessage.error('获取数据失败');
        console.error(err);
    }
}

const reNameHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(updateBook({ id: selectedBookId.value, name: form2.name }));
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
        searchBook();
        reNamingVisile.value = false;
    } else {
        ElMessage.error('更新失败');
        console.error(err);
    }
}

const deleteCBookHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(updateBook({ id: selectedBookId.value, isDelete: 1 }));
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
        ElMessage.success('删除成功');
        searchBook();
        deleteVisile.value = false;
    } else {
        ElMessage.error('删除失败');
        console.error(err);
    }
}

onMounted(() => {
    getBooksHandle();
})
</script>
<style lang="less" scoped>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

.intro {
    word-break: break-all;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    /* 超出几行省略 */
    overflow: hidden;
    margin-bottom: 20px;
    font-size: var(--te-size-font-4);
    color: var(--te-color-font-dark-3);
}

.time {
    font-size: var(--te-size-font-3);
    color: var(--te-color-font-dark-3);
}

.card-header {
    display: flex;
    justify-content: space-between;
}

.card-content {
    cursor: pointer;
}

.more {
    cursor: pointer;
}

.popour-list {
    list-style: none;
    padding: 0;
}

.popour-list-item {
    padding: 10px;
    cursor: pointer;
}

.popour-list-item:hover {
    background-color: #f5f7fa;
}
</style>